package com.azt.provider.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ServiceException;
import com.azt.api.dto.*;
import com.azt.api.enums.*;
import com.azt.api.pojo.*;
import com.azt.api.service.*;
import com.azt.model.AjaxJson;
import com.azt.model.page.Pagination;
import com.azt.model.page.TPagination;
import com.azt.provider.mapper.*;
import com.azt.provider.model.QuoteItemCategory;
import com.azt.utils.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.StringUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecgframework.poi.excel.ExcelToHtmlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 新版询价
 *
 * @author 张栋 2016年9月6日上午9:58:47
 */
@Service
@Transactional
public class EnqEnquiryServiceImpl implements EnqEnquiryService {


	private static final Logger LOGGER = Logger.getLogger(EnqEnquiryServiceImpl.class);

    /*询价*/
    @Autowired
    private EnqProjectMapper enqProjectMapper;
    @Autowired
    private EnqEnquiryMapper enquiryMapper;
    @Autowired
    private EnqEnquiryItemMapper itemMapper;

	/*报价*/
	@Autowired
	private EnqQuoteMapper enqQuoteMapper;

	@Autowired
	private EnqQuoteItemMapper enqQuoteItemMapper;


	/*预算*/
	@Autowired
	private EnqBudgetMapper enqBudgetMapper;

	@Autowired
	private EnqBudgetItemMapper  enqBudgetItemMapper;



	@Autowired
	private ProCategoryService  categoryService;

	@Autowired
	private ProRepositoryService proRepositoryService;

	@Autowired
	private ProRepositoryTitleService  repositoryService;
	
	@Autowired
	private CompanyService  companyService;

	@Autowired
	private UserService userService;

	@Autowired
	private MsgConfigService msgConfigService;

	@Autowired
	private CompanyCategoryService companyCategoryService;

	@Autowired
	private CompanyBusinessMapper companyBusinessMapper;


	@Autowired
	private IntegralService integralService;

	@Override
	public List<IndexEnquiry> findIndexEnquiry(Integer companyId, int pageSize) {
		return enquiryMapper.findIndexEnquiry(companyId, pageSize);
	}

	@Override
	public int getIndexEnquiryCount() {
		return enquiryMapper.getIndexEnquiryCount();
	}

	@Override
	public EnqEnquiry getEnquiryById(int enquiryId) {
		return enquiryMapper.selectByPrimaryKey(enquiryId);
	}

	@Override
	public Pagination getEnqEnquiryPage(int pageno, int pagesize, Map<String, String> searchMap) {

		Page<Object> startPage = PageHelper.startPage(pageno, pagesize);
		
		List<EnqEnquiry> enqEnquiryByPage = enquiryMapper.getEnqEnquiryList(searchMap);

		for (EnqEnquiry enqEnquiry : enqEnquiryByPage) {
			enqEnquiry.setHasQuoteAnalysis(ifAnalysisQuote(enqEnquiry.getId()));
		}
		
		Pagination p = new Pagination(startPage,enqEnquiryByPage);
		p.setList(enqEnquiryByPage);
		p.setParams(searchMap);
		return p;
	}

	@Override
	public Pagination getQuoteAnalysisPage(int pageno, int pagesize, Map<String, String> searchMap) {

		Page<Object> startPage = PageHelper.startPage(pageno, pagesize);

		List<EnqQuoteListDto> quoteAnalysisPage = enquiryMapper.getQuoteAnalysisList(searchMap);

		Pagination p = new Pagination(startPage,quoteAnalysisPage);
		p.setList(quoteAnalysisPage);
		p.setParams(searchMap);
		return p;
	}

    @Override
    public Integer ifAnalysisQuote(Integer enquiryId) {
        return enquiryMapper.ifAnalysisQuote(enquiryId);
    }

    @Override
	public EnqEnquiry getEnquiryById(Integer id) {
        return enquiryMapper.getEnqEnquiryById(id);
	}

	@Override
	public void saveOrUpdateEnq(EnqEnquiry enquiry) {
		if(enquiry.getId()==null){
			enquiryMapper.insert(enquiry);
		}else{
			enquiryMapper.updateByPrimaryKey(enquiry);
		}
	}

	@Override
	public void saveOrUpdateEnquiryItem(Integer enquiryid, List<EnqEnquiryItem> item) {

		// 先删除之前所有的列
		EnqEnquiryItem itemfordel = new EnqEnquiryItem();
		itemfordel.setEnquiryId(enquiryid);
		itemMapper.delete(itemfordel);

		//2016.8.23现在不仅要保存三级类目,还要保存顶级目录,分析的时候,匹配多个一时,不太好带入顶级类目,所以在此页面上由于有重复项,不好处理,因此在代码里处理
		for(EnqEnquiryItem i:item){
			i.setEnquiryId(enquiryid);
			Integer categorySId = i.getCategorySId();
			if(categorySId==null){
				Integer categoryPId= i.getCategoryPId();
				Category entity = categoryService.getCategorysById(categoryPId);
				i.setCategoryPId(categoryPId);
				Category topcategory = getTopCategoryByBottomCategory(entity);
				i.setCategorySId(topcategory.getId());
				i.setCategoryS(topcategory);
			}else{
				i.setCategoryPId(i.getCategoryPId());
				i.setCategorySId(i.getCategorySId());
			}
			itemMapper.insert(i);
		}
		
	}

	private Category getTopCategoryByBottomCategory(Category category) {
		if(category.getPid()==0){
			return category;
		}else{
			Category entity = categoryService.getCategorysById(category.getPid());
			return getTopCategoryByBottomCategory(entity);
		}
	}

	@Override
	public List<EnqEnquiryItem> getEnquiryItem(Integer enquiryid) {
		EnqEnquiry enquiry = enquiryMapper.getEnqEnquiryById(enquiryid);
		
		EnqEnquiryItem item = new EnqEnquiryItem();
		item.setEnquiryId(enquiryid);
		List<EnqEnquiryItem> select = itemMapper.select(item);
		for (int i = 0; i < select.size(); i++) {
			EnqEnquiryItem enitem = select.get(i);
			enitem.setEnqEnquiry(enquiry);
			Integer pid = enitem.getCategoryPId();

			if(pid!=null){
				Category cp = categoryService.getCategorysById(pid);
				enitem.setCategory(cp);
			}else{
				enitem.setCategory(null);
			}

			Category sp = categoryService.getCategorysById(enitem.getCategorySId());
			enitem.setCategoryS(sp);
			
		}
		return select;
	}

	@Override
	public String excelToHtml(String excelpath) {
		Workbook wb;
		try {
			wb = toWorkbook(excelpath);
			int numberOfSheets = wb.getNumberOfSheets();
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < numberOfSheets; i++) {
				String allHtml = ExcelToHtmlUtil.toAllHtml(wb, i);
				sb.append(allHtml);
			}
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 根据地址。转换成workbook
	 * 
	 * @param path
	 * @return
	 * @throws Exception
	 * @author 张栋 2016年5月19日下午2:26:02
	 */
	private Workbook toWorkbook(String path) throws Exception {
		URL url = new URL(path);
		InputStream file = url.openStream();
		Workbook wb = null;
		try {
			// 2003
			wb = new HSSFWorkbook(file);
		} catch (Exception e) {
			file.close();
			// 2007
			try {
				file = url.openStream();
				wb = new XSSFWorkbook(file);
			} catch (Exception e1) {
				file.close();
				// 重新测试一次 ，更改后缀
				// 计划重新上传，并改后缀
				String key = OSSFileUtils.getKey(path, null);
				String[] split = StringUtils.split(key, ".");
				StringBuffer sb = new StringBuffer();
				sb.append(split[0]);
				sb.append("_c");
				if (split[1].equals("xls")) {
					sb.append(".xlsx");
				} else {
					sb.append(".xls");
				}

				String copy = OSSFileUtils.copy(key, sb.toString());
				url = new URL(copy);
				file = url.openStream();
				try {
					wb = new HSSFWorkbook(file);
				} catch (Exception ex) {
					wb = new XSSFWorkbook(file);
				}
			}
		}

		return wb;
	}

	
	@Override
	public EnqEnquiry changeEnquiryState(Integer id, Integer prostate) {
		EnqEnquiry enqEnquiry =enquiryMapper.selectByPrimaryKey(new EnqEnquiry(id));
		enqEnquiry.setState(prostate);
		enquiryMapper.updateByPrimaryKey(enqEnquiry);
		return enqEnquiry;
	}



	/**
	 *
	 * Created by 张栋 on 2017/4/1 13:17
	 */
	public boolean isAdminOrFinance(Integer userid){
		//判断是不是  管理员/财务
		List<UserEnum> userenum  = new ArrayList<>();
		userenum.add(UserEnum.cadmin);
		userenum.add(UserEnum.cfinance);
		boolean hasPermission = userService.getUserAuthorityByUserId(userid, userenum);
		return hasPermission;
	};





	@Override
	public TPagination<EnqProjListDto> getMyProject(Integer pageNo, int pageSize, EnqProjSearchDto dto) {

		List<Integer> companyids = new ArrayList<>();
		//这个优先,如要有这个字段, 则只查这个公司的
		if(dto.getOnecustomerId()!=null &&dto.getOnecustomerId()!=0){
			companyids.add(dto.getOnecustomerId());
		}else{
			boolean hasPermission = isAdminOrFinance(dto.getUserId());
			companyids.add(dto.getCustomerId());
			if(hasPermission){//如果有权限,则查总公司与子公司的
				//获取公司下的所有子公司
				List<Company> companies = companyService.allBranchCompany(dto.getCustomerId());
				if(companies!=null){
					for (Company company : companies) {
						companyids.add(company.getId());
					}
				}
			}
		}



		if(pageNo==null)pageNo=1;
		Page<Object> page = PageHelper.startPage(pageNo, pageSize);
		List<EnqProjListDto>  list =  enquiryMapper.getMyProject(dto,companyids);
		TPagination p = new TPagination<EnqProjListDto>(page,list);
		return p ;
	}

	@Override
	public EnqProject getEnqProjectById(Integer projid) {
        EnqProject project = enqProjectMapper.selectByPrimaryKey(new EnqProject(projid));
        return project;
	}

	@Override
	public TPagination<EnqProjDetailDto> getEnqProjDetail(Integer projid, Integer qtype, Integer userid, Integer companyId, Integer pageNo, Integer pageSize) {

		boolean hasPermission = isAdminOrFinance(userid);

		List<Integer> companyids =null;
		//有权限可以看到当前公司与分公司发的询价
		if(hasPermission){
			companyids = new ArrayList<>();
			companyids.add(companyId);
			List<Company> companies = companyService.allBranchCompany(companyId);
			if(companies!=null){
				for (Company company : companies) {
					companyids.add(company.getId());
				}
			}
		}

		//'1.设计需求 2.采购询价',
		Page<Object> page = PageHelper.startPage(pageNo, pageSize);
        List<EnqProjDetailDto> enqDetail = enquiryMapper.getEnqProjDetail(projid,qtype,userid,companyids);
        TPagination<EnqProjDetailDto> detail = new TPagination<>(page, enqDetail);


        //2017.3.14 杨程,孙俊 设计更改了, 所有人都可以看到该项目下的所有询价,再由规则:创建询价:只有创建项目的人才能发布该项目下面的询价,所以该项目下面其实也只能有一个人,

//        Page<Object> page = PageHelper.startPage(pageNo, pageSize);
//        List<EnqProjDetailDto> enqDetail = enquiryMapper.getEnqProjDetail(projid,qtype,null,null);
//        TPagination<EnqProjDetailDto> detail = new TPagination<>(page, enqDetail);
        return detail;
	}

    @Override
    public TPagination<EnqBudgetExt> getBudGetDetail(Integer projid, Integer budgettype, Integer userid, Integer companyId, Integer pageNo, Integer pageSize) {

		//判断是不是  管理员/财务
		boolean hasPermission = isAdminOrFinance(userid);
		List<Integer> companyids =  new ArrayList<>();
		companyids.add(companyId);
		//管理/财务 ,  可以看到自己公司与分公司下的预算 ,普通的可以看到当前公司下的预算
		if(hasPermission){
			List<Company> companies = companyService.allBranchCompany(companyId);
			if(companies!=null){
				for (Company company : companies) {
					companyids.add(company.getId());
				}
			}
		}
		Page<Object> page = PageHelper.startPage(pageNo, pageSize);
        List<EnqBudgetExt> select=enqBudgetMapper.getEnqBudgetList(projid,budgettype==-1?null:budgettype,companyids);
		TPagination tpage = new TPagination<EnqBudgetExt>(page,select);
        return tpage;
    }

    @Override
    public TPagination<PushEnquiryListDto> getPushEnquiryList(PushEnqirySearchDto psd , Integer pageNo , Integer pageSize) {
		Page<Object> page = PageHelper.startPage(pageNo, pageSize);
		List<PushEnquiryListDto> pushList = enquiryMapper.getPushEnquiryList(psd);
		TPagination<PushEnquiryListDto> list = new TPagination<>(page, pushList);
		return list;
    }

	@Override
	public TPagination<PushEnquiryListDto> getWechatPushEnquiryList(PushEnqirySearchDto psd , Integer pageNo , Integer pageSize) {
		Page<Object> page = PageHelper.startPage(pageNo, pageSize);
		List<PushEnquiryListDto> pushList = enquiryMapper.getWechatPushEnquiryList(psd);
		TPagination<PushEnquiryListDto> list = new TPagination<>(page, pushList);
		return list;
	}

    @Override
    public Integer getPushEnquiryCount(Integer companyId) {
        return enquiryMapper.getPushEnquiryCount(companyId);
    }

	@Override
	public Integer getMyQuoteCount(@Param("userId") Integer userId, @Param("companyId") Integer companyId, @Param("qtype") Integer qtype) {
		return enquiryMapper.getMyQuoteCount(userId , companyId , qtype);
	}

	@Override
    public TPagination<QuoteListDto> getMyQuoteList(PushEnqirySearchDto psd, Integer pageNo, Integer pageSize) {
		Page<Object> page = PageHelper.startPage(pageNo, pageSize);
		List<QuoteListDto> pushList = enquiryMapper.getMyQuoteList(psd);
		TPagination<QuoteListDto> list = new TPagination<>(page, pushList);
		return list;
    }

	@Override
	public List<QuoteListDto> getCenterQuoteList(@Param("userId") Integer userId, @Param("companyId") Integer companyId) {

		Page<Object> page = PageHelper.startPage(1, 5);
		List<QuoteListDto> pushList = enquiryMapper.getCenterQuoteList(userId , companyId);
		return pushList;
	}

	@Override
	public EnqBudgetDetailWrap getBudGetDetailWrap(Integer budgetId) {

		//查出对应的询价id
		EnqBudget enqBudget = enqBudgetMapper.selectOne(new EnqBudget(budgetId));
		EnqEnquiry enqEnquiry = null;
		if(null!=enqBudget){
			Integer enquiryId = enqBudget.getEnquiryId();
			enqEnquiry = enquiryMapper.getEnqEnquiryById(enquiryId);
		}

		/*查出当前预算下的子表*/
		EnqBudgetItem enqBudgetItem = new EnqBudgetItem();
		enqBudgetItem.setBudgetId(budgetId);
		List<EnqBudgetItem> select = enqBudgetItemMapper.select(enqBudgetItem);

		List<EnqQuoteItemExt> all = new ArrayList<>();
		Set<EnqBgetCompInfo> infos = new HashSet<>();
		for (EnqBudgetItem budgetItem : select) {
			/*类目id*/
			Integer categroyId = budgetItem.getCategroyId();
			/*询价id*/
			Integer quoteId = budgetItem.getQuoteId();
			List<EnqQuoteItemExt> list =  enqQuoteItemMapper.getBudgetDetailByQIDAndCID(quoteId,categroyId);

			if(!list.isEmpty()){
				//组件 筛选列表
				EnqQuoteItemExt enqBudgetDetail = list.get(0);
				Integer companyId = enqBudgetDetail.getCompanyId();
				String companyName = enqBudgetDetail.getCompanyName();
				EnqBgetCompInfo compInfo =new EnqBgetCompInfo(companyId,companyName);
				infos.add(compInfo);
			}
			all.addAll(list);

		}
		/*组装数据*/
		EnqBudgetDetailWrap  wrap = new EnqBudgetDetailWrap();
		wrap.setDetailList(all);
		wrap.setEnqBudget(enqBudget);
		List<EnqBgetCompInfo> infolist = new ArrayList<EnqBgetCompInfo>();
		infolist.addAll(infos);
		wrap.setCompanys(infolist);
		wrap.setEnqEnquiry(enqEnquiry);
		return wrap;
	}

	@Override
	public List<EnqBgetCreate> getEnqBgetCreate(List<Integer> quoteids) {
		List<EnqBgetCreate> list = enqQuoteMapper.getEnqBgetCreate(quoteids);
		return list;
	}

	@Override
	public List<EnqQuoteItemExt> getBudGetDetail(Integer quoteId) {
		List<EnqQuoteItemExt> list =  enqQuoteItemMapper.getBudgetDetailByQIDAndCID(quoteId,null);
		return list;
	}

	@Override
	public Integer budgetDesignSave(Integer quoteid, Integer userid, Integer companyId) {
		/*获取询价id*/
		EnqQuote  quote = enqQuoteMapper.selectOne(new EnqQuote(quoteid));
		Integer enquiryId = quote.getEnquiryId();

		/*获取projectid*/
		EnqEnquiry enqEnquiry = enquiryMapper.selectOne(new EnqEnquiry(enquiryId));
		Integer projectId = enqEnquiry.getProjectId();

        /*查  categroyNames*/
        String categoryNames = enqQuoteMapper.getCategoryNames(quoteid);

		/*创建主表*/
		EnqBudget budget = new EnqBudget();
		//设计预算
		budget.setQtype(1);
        budget.setUserId(enqEnquiry.getUserId());
		budget.setCustomerId(enqEnquiry.getCustomerId());

		budget.setProjectId(projectId);
		budget.setEnquiryId(enquiryId);
        budget.setCategroyNames(categoryNames);
        enqBudgetMapper.insert(budget);

        /*创建子表 ,报价详情里有多少个类目,就有多少个子表*/
        List<QuoteItemCategory> quoteItemCategory = enqQuoteMapper.getQuoteItemCategory(quoteid);
        for (QuoteItemCategory itemCategory : quoteItemCategory) {
            EnqBudgetItem  item = new EnqBudgetItem();
            item.setBudgetId(budget.getId());
            item.setCategroyId(itemCategory.getCategoryid());
            item.setCategroyName(itemCategory.getCategoryname());
            item.setQuoteId(quoteid);
            enqBudgetItemMapper.insert(item);
        }

        return budget.getId();
	}
	@Override
	public EnqBudget budgetPurchaseSave(Integer enqid, List<EnqBgetPchaseSave> checked, Integer userid, Integer companyid) {
		EnqEnquiry enquiry = enquiryMapper.selectByPrimaryKey(new EnqEnquiry(enqid));
		Integer projectid = enquiry.getProjectId();

		//创建主表
		EnqBudget budget = new EnqBudget();
		//2016,12,29 胡子强 , 因为改成自己发的询价的报价,只能自己转预算,所以这边的 预算人员  就是指 询价人
		budget.setUserId(enquiry.getUserId());
		budget.setCustomerId(enquiry.getCustomerId());

		budget.setEnquiryId(enqid);
		budget.setProjectId(projectid);
		budget.setQtype(2);
		enqBudgetMapper.insert(budget);

		//创建子表
		StringBuffer sb = new StringBuffer();
		boolean isfirst =true;
		for (EnqBgetPchaseSave bget : checked) {
			Integer categoryId = bget.getCategoryId();
			Category category = categoryService.getCategorysById(categoryId);
			//获取类目名称
			String name = category.getName();

			EnqBudgetItem  item = new EnqBudgetItem();
			item.setBudgetId(budget.getId());
			item.setCategroyId(bget.getCategoryId());
			item.setCategroyName(name);
			item.setQuoteId(bget.getQuoteid());
			enqBudgetItemMapper.insert(item);

			if(isfirst){
				isfirst=false;
			}else{
				sb.append(",");
			}
			sb.append(name);
		}

		//更新主表类目名称
		budget.setCategroyNames(sb.toString());
		enqBudgetMapper.updateByPrimaryKeySelective(budget);
		return budget;
	}

	@Override
	public EnqProjectExt getEnqProjectExtById(Integer projid) {
		return enqProjectMapper.getEnqProjectExtById(projid);
	}

	@Override
    public QuoteEnquiryDto getQuoteInfo(Integer id  , Integer companyId) {
        return enquiryMapper.getQuoteInfo(id , companyId);
    }

	@Override
	public QuoteEnquiryDto getBaseEnquiryInfo(Integer id) {
		return enquiryMapper.getBaseEnquiryInfo(id);
	}

	@Override
	public List<EnqProject> getProjeListBYUserid(Integer userid) {
		EnqProject  pro = new EnqProject();
		pro.setUserId(userid);
		pro.setState(1);
		return enqProjectMapper.select(pro);
	}

	@Override
	public EnqEnquiry savePurchaseExternal(EnqEnquiry enqa) {
		boolean iseditor = enqa.getId()!=null;

		//报价是否含税（ 1.含增税 2.普税 3.不含税）',
		if(enqa.getTaxPrice()==null){
			enqa.setTaxPrice(3);
			enqa.setTaxInstro(null);//清掉税率值
		}

		//'报价是否含运费（1:报价含运费2：报价不含运费）',
		if(enqa.getShipPrice()==null){
			enqa.setShipPrice(2);
		}

		/*空则为null*/
		String excelpath = enqa.getExcelpath();
        if(StringUtils.isEmpty(excelpath)){
            enqa.setExcelpath(null);
        }

        /*质保要求:其他,否则清掉其他里的内容*/
        if(enqa.getQuality()==-1){
        	enqa.setQuality(null);
		}else{
			enqa.setGuaranteeinfo(null);
		}

		//附件
        String attachfile = enqa.getAttachfile();
        if (StringUtils.isEmpty(attachfile)){
            enqa.setAttachfile(null);
        }

		//0:待审核,1:已发布,2:不通过,3:重新审核4：已关闭 5：已截止
		if(iseditor){
			EnqEnquiry oldEnq = enquiryMapper.getEnqEnquiryById(enqa.getId());
			Integer state = oldEnq.getState();
			if(state==2||state==3){//如果原来的状态为不通过,新的为重新审核
				enqa.setState(3);
				//退回原因
				enqa.setBackreason(oldEnq.getBackreason());
				//是否发送过短信
				enqa.setHadsendsms(oldEnq.getHadsendsms());
			}else if(state==0){
				enqa.setState(0);
			}else{
				enqa.setState(3);
			}

			//编辑
			sendOurMessage(enqa,1);

		}else{
			//新增
			sendOurMessage(enqa,0);
			enqa.setState(0);
			enqa.setFirstPass(1);
		}


		Integer projectId = enqa.getProjectId();
		if(projectId==null||projectId==0){
			/*创建新的*/
			/*保存项目*/
			EnqProject enqProject = enqa.getEnqProject();
			enqProject.setState(1);
			enqProject.setRemoved(0);
			enqProjectMapper.insert(enqProject);
			/*保存询价*/
			enqa.setProjectId(enqProject.getId());
			enquiryMapper.insert(enqa);

			/*保存item*/
			List<EnqEnquiryItem> items = enqa.getItems();
			if(items!=null ){
				for (EnqEnquiryItem item : items) {
					//数量为空,不保存
					if(item.getQuantity()==null){
						continue;
					}
					if(!StrUtil.hasBlank(item.getProductName(),item.getUnit())){
						item.setEnquiryId(enqa.getId());
						item.setProjectId(enqa.getProjectId());
                        itemMapper.insert(item);
                        saveRepository(item);
                    }
				}
			}

			return enqa;
		}else{
			/*选择已经有的*/
			if(iseditor){
				enquiryMapper.updateByPrimaryKey(enqa);
				//删除掉原有的item
				EnqEnquiryItem enqitem = new EnqEnquiryItem();
				enqitem.setEnquiryId(enqa.getId());
				int delete = itemMapper.delete(enqitem);
			}else{
				enquiryMapper.insert(enqa);
			}

			/*保存item*/
			List<EnqEnquiryItem> items = enqa.getItems();
			if(items!=null ) {
				for (EnqEnquiryItem item : items) {
					//数量为空,不保存
					if(item.getQuantity()==null){
						continue;
					}
					//名称,单位为空,则不保存
					if(!StrUtil.hasBlank(item.getProductName(),item.getUnit())){
						item.setEnquiryId(enqa.getId());
						item.setProjectId(enqa.getProjectId());
						try {
							itemMapper.insert(item);
                            saveRepository(item);
                        } catch (Exception e) {
							e.printStackTrace();
						}
					}

				}
			}

			return enqa;
		}

	}

    private void saveRepository(EnqEnquiryItem item) {
        String productname = item.getProductName().trim();
        String secret = PasswordUtil.MD5_16(productname);
        Integer categoryPid  = item.getCategoryPId();
        //保存至仓库
        ProRepository repositoryBymd5AndPcat = proRepositoryService.getRepositoryBymd5AndPcat(secret, categoryPid);
        if(repositoryBymd5AndPcat==null){
            //是空的时候,说明数据库没有,需要添加到数据库
            ProRepository p = new ProRepository();
            p.setPid(categoryPid);
            p.setTitle(productname);
            p.setSecret(secret);
            proRepositoryService.saveOrupdateRepository(p);
        }
    }

    //通知运营   type ==1,编辑  type==0 新增
	private void sendOurMessage(EnqEnquiry enqa,Integer type) {
		Map<String,String> param = new HashMap<>();
		Integer customerId = enqa.getCustomerId();
		Company company = companyService.getCompanyById(customerId);
		param.put("company",company.getCompanyName());
		Integer qtype = enqa.getQtype();
		String name = qtype==1?"预算":"采购";
		param.put("aa",name);
		param.put("enqname",enqa.getEnquiryName());
		if(type==0){
//			msgConfigService.sendMessage("ENQ_SAVE_TIP","ENQ_SAVE_TIP",param);
			msgConfigService.sendMessage("ENQ_SAVE_TIP",param,null,new ArrayList());
		}else{
			msgConfigService.sendMessage("ENQ_EDIT_TIP",param,null,new ArrayList());
//			msgConfigService.sendMessage("ENQ_EDIT_TIP","ENQ_EDIT_TIP",param);
		}

	}

	@Override
	public List<EnqBgetPurchaseCreate> getEnqBgetPchurCreate(Integer enqid , List<Integer> quoteids) {
            
	    /**
	     * 查询麻烦后期优化
	     * Created by 张栋 on 2016/11/8 10:05
	     */
		//拿到报价的系统,以及系统下对应的所有产品
		/* 查多个报价下的多个enq_quote_item 并去重*/
		List<EnqBgetPurchaseCreate> pcreate = enqBudgetMapper.getBgetCatAndProduct(enqid ,quoteids);
		//报价下面对应的公司
		List<EnqBgetPchaseCompany> companyyyy =  enqBudgetMapper.getBgetCatAndProduct2(quoteids);
		//根据每个类目,查,该类目下的报价商的信息.
		for (EnqBgetPurchaseCreate bpc : pcreate) {
			Integer categoryid = bpc.getCategoryid();
            //根据类别与报价id查所有供应商信息
			//报价对应的公司,
			//复制一份出来, 不然会从缓存取的同一个对象
			List<EnqBgetPchaseCompany> companies = new ArrayList<>();
			for (EnqBgetPchaseCompany enqBgetPchaseCompany : companyyyy) {
				EnqBgetPchaseCompany c = new EnqBgetPchaseCompany();
				c.setCompanyId(enqBgetPchaseCompany.getCompanyId());
				c.setCompanyName(enqBgetPchaseCompany.getCompanyName());
				c.setQuoteid(enqBgetPchaseCompany.getQuoteid());
				companies.add(c);
			}

            for (EnqBgetPchaseCompany company : companies) {
				company.setCategorySId(categoryid);
                //根据报价id,类别,公司查该公司下的所有商品报价
                List<Map> prices = enqBudgetMapper.getBgetCatAndProduct3(categoryid,company.getCompanyId(),bpc.getEnquiryId(),quoteids);

				List<Double> totalprice = new ArrayList<>();
				List<Double> unitprice = new ArrayList<>();
				for (Map price : prices) {
					totalprice.add(new BigDecimal(price.get("totalPrice").toString()).doubleValue());
					unitprice.add(new BigDecimal(price.get("unitprice").toString()).doubleValue());
				}
                company.setPrice(totalprice);
                company.setUnitprice(unitprice);
            }
			bpc.setCompany(companies);
		}
		return pcreate;
	}

    /**
     *
     * 导出询价清单    固定的格式
     * @param enquiryId
     * @param companyId
     */
    @Override
    public void exportEnquiryItem(Integer enquiryId , Integer qtype , Integer companyId , HttpServletResponse response , HttpServletRequest request) {
		Iterable<EnqEnquiryItem> exportItem = (Iterable<EnqEnquiryItem>)itemMapper.getExportItem(enquiryId, companyId);
		List<Map<String, Object>> titles = generateQuoteItemTitles();
		try {
			ExcelUtil.export((qtype == 1 ? "预算" : "采购")+"询价商品清单", titles, exportItem, new EnqEnquiryitemRenderer(), response , request);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

    /**
     *
     * 导出询价清单    固定的格式  平台内部使用  增加系统那一列
     * @param enquiryId
     * @param companyId
     */
    @Override
    public void exportEnquiryItemForTest(Integer enquiryId , Integer qtype , Integer companyId , HttpServletResponse response , HttpServletRequest request) {
		Iterable<EnqEnquiryItem> exportItem = (Iterable<EnqEnquiryItem>)itemMapper.getExportItem(enquiryId, companyId);
		List<Map<String, Object>> titles = generateQuoteItemTitlesForTest();
		try {
			ExcelUtil.export((qtype == 1 ? "预算" : "采购")+"询价商品清单", titles, exportItem, new EnqEnquiryitemRendererTest(), response , request);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Map<String, Object> importQuoteItem(String  excelPath, String fileName , Integer quoteId , Integer enquiryId) {
		Map<String , Object> res = new HashMap<String , Object>();
		res.put("enquiryId", enquiryId);
		res.put("success" , false);
		if (excelPath == null || fileName == null) {
			res.put("msg" , "报价文件不存在！");
			return res;
		}
		String ext = FileUtil.getFileExt(fileName);
		if (ext == null || (!"xls".equals(ext) && !"xlsx".equals(ext))) {
			res.put("msg" , "不是一个有效的Excel文件！");
			return res;
		}
		try {

			Workbook wb = ExcelUtil.getWorkbookCompatible(excelPath);
			Sheet sheet = wb.getSheetAt(0);
			List<EnqQuoteItem> items = new ArrayList<EnqQuoteItem>();
			StringBuffer titleMsg = new StringBuffer();
			for (int i = 1; i <= sheet.getLastRowNum(); i++) {
				Row row = sheet.getRow(i);
				if (row == null) {
					continue;
				}
				EnqQuoteItem qi = new EnqQuoteItem();
				Cell enquiryItemIdCell = row.getCell(0);
				Cell productnameCell = row.getCell(1);
				Cell industryCell = row.getCell(2);
				Cell modelCell = row.getCell(3);
				Cell unitCell = row.getCell(4);
				Cell countCell = row.getCell(5);
				Cell unitpriceCell = row.getCell(6);
				Cell subtotalCell = row.getCell(7);
				if (productnameCell == null && industryCell == null && unitCell == null && unitpriceCell == null
						&& countCell == null) {
					continue;
				}
				if (productnameCell.getCellType() == HSSFCell.CELL_TYPE_BLANK
						&& industryCell.getCellType() == HSSFCell.CELL_TYPE_BLANK
						&& unitCell.getCellType() == HSSFCell.CELL_TYPE_BLANK
						&& unitpriceCell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
					continue;
				}
				if (unitpriceCell == null || unitpriceCell.getCellType() == HSSFCell.CELL_TYPE_BLANK || ExcelUtil.getStringCellValue(unitpriceCell) == null) {
					continue;
				}
				// 设备or产品名称
				if (productnameCell == null) {
					titleMsg.append("第" + i + "条产品,设备名称不能空!\n");
					continue;
				}
				String productname = ExcelUtil.getStringCellValue(productnameCell);
				if (StringUtil.isEmpty(productname)) {
					titleMsg.append("第" + i + "条产品,设备名称不能空!\n");
					continue;
				} else {
					qi.setProductName(productname);
				}
				// 品牌
				String brand = ExcelUtil.getStringCellValue(industryCell);
				//if (StringUtil.isEmpty(brand)) {
				//	titleMsg.append("第" + i + "条产品,品牌不能空!\n");
				//	continue;
				//} else {
				//}
					qi.setBrand(brand == null ? "" : brand);
				// 型号
				String model = ExcelUtil.getStringCellValue(modelCell);
				//if (StringUtil.isEmpty(model)) {
				//	titleMsg.append("第" + i + "条产品,型号不能空!\n");
				//	continue;
				//} else {
				//}
					qi.setModel(model == null ? "" : model);
				// 单位
				if (unitCell == null) {
					titleMsg.append("第" + i + "条产品,单位不能空!\n");
					continue;
				}
				String unit = ExcelUtil.getStringCellValue(unitCell);
				if (StringUtil.isEmpty(unit)) {
					titleMsg.append("第" + i +"条产品,单位不能空!\n");
					continue;
				} else {
					qi.setUnit(unit);
				}
				// 数量
				if (countCell == null || countCell.getCellType() != HSSFCell.CELL_TYPE_NUMERIC) {
					titleMsg.append("第" + i + "条产品,数量必须是数字且必填!\n");
					continue;
				}
				// enquiryItemId
				if (enquiryItemIdCell != null && enquiryItemIdCell.getCellType() != HSSFCell.CELL_TYPE_NUMERIC) {
					titleMsg.append("第" + i + "条产品,编号必须是数字！!\n");
					continue;
				}
				String eiicell = ExcelUtil.getStringCellValue(enquiryItemIdCell);
				if(!StringUtil.isEmpty(eiicell)){
					Integer enquiryItem = Integer.parseInt(eiicell);
					qi.setEnquiryItemId(enquiryItem);
					EnqEnquiryItem enqEnquiryItem = itemMapper.selectByPrimaryKey(enquiryItem);
					if (enqEnquiryItem == null) {
						titleMsg.append("第" + i +"条产品,编号:"+enquiryItem+"的清单项已不存在，建议退回给供应商重新上传最新的报价单！\n");
						continue;
					}
					if(enquiryId != null){
						if(enqEnquiryItem.getEnquiryId().compareTo(enquiryId) == 0){
							qi.setCategorySId(enqEnquiryItem.getCategorySId());
							qi.setCategoryName(categoryService.getCategorysById(qi.getCategorySId()).getName());
						}else{
							titleMsg.append("第" + i +"条产品,编号错误，不是该询价下的数据!\n");
							continue;
						}
					}else{
						titleMsg.append("数据问题，询价Id不存在\n");
						break;
					}
				}else{
					titleMsg.append("第" + i +"条产品,编号不为空!\n");
					continue;
				}
				qi.setQuantity(CommonUtil.round(ExcelUtil.getDoubleCellValue(countCell) , 4 , BigDecimal.ROUND_HALF_UP));
				// 单价
				if (unitpriceCell == null || unitpriceCell.getCellType() != HSSFCell.CELL_TYPE_NUMERIC) {
					titleMsg.append("第" + i + "条产品,单价必须是数字且必填!\n");
					continue;
				}
				qi.setUnitprice(CommonUtil.round(ExcelUtil.getDoubleCellValue(unitpriceCell) , 2 , BigDecimal.ROUND_HALF_UP));
				// 金额
				double subtotal = 0.0;
//				if (subtotalCell == null || (subtotalCell.getCellType() != HSSFCell.CELL_TYPE_FORMULA
//						&& subtotalCell.getCellType() != HSSFCell.CELL_TYPE_NUMERIC)) {
				subtotal = ExcelUtil.mul(qi.getQuantity(),qi.getUnitprice());
//				}else{
//					subtotal = ExcelUtil.getDoubleCellValue(subtotalCell);
//					BigDecimal bg = new BigDecimal(subtotal);
				//subtotal = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//					subtotal = bg.doubleValue();
//				}
				if (subtotal != 0) {
					qi.setTotalPrice(CommonUtil.round(subtotal , 2 , BigDecimal.ROUND_HALF_UP));
				} else {
					//2016.9.18 张栋  需求变更,为0的也可以上传
//					qi.setSubtotal(subtotal);
					continue;
				}
				// 技术参数描述
				Cell descrCell = row.getCell(8);
				if (descrCell != null){
					String dcl = ExcelUtil.getStringCellValue(descrCell);
					if(StringUtils.isNotBlank(dcl)){
						qi.setDescr(ExcelUtil.getStringCellValue(descrCell));
					}else{
						qi.setDescr("");
					}
				} else {
					qi.setDescr("");
				}
				qi.setQuoteId(quoteId);
				items.add(qi);
			}

			if (items.isEmpty()) {
				titleMsg.append("没有可导入数据!\n");
			} else {
				res.put("items", items);
			}
			if("".equals(titleMsg.toString())){
				res.put("success", true);
            }else{
				res.put("success", false);
            }
			res.put("msg", "".equals(titleMsg.toString()) ? "" : titleMsg.substring(0 , titleMsg.lastIndexOf("\n")));
			return res;
		} catch (Exception e) {
			e.printStackTrace();
            if(e instanceof org.apache.poi.poifs.filesystem.OfficeXmlFileException){
                res.put("msg" , "文件分析时出错！");
            }
            if (e instanceof ServiceException) {
                throw (ServiceException) e;
            } else {
                LOGGER.error( "报价采析报错！", e);
                res.put("msg" , "文件“"+fileName+"”内容格式不正确，请确认模板是否被修改");
			}
		}

		return res;
	}


	@Override
	public Map<String, Object> importQuoteItem(String  excelPath, String fileName , Integer enquiryId) {
		Map<String , Object> res = new HashMap<String , Object>();
		res.put("enquiryId", enquiryId);
		res.put("success" , false);
		if (excelPath == null || fileName == null) {
			res.put("msg" , "报价文件不存在！");
			return res;
		}
		String ext = FileUtil.getFileExt(fileName);
		if (ext == null || (!"xls".equals(ext) && !"xlsx".equals(ext))) {
			res.put("msg" , "不是一个有效的Excel文件！");
			return res;
		}
		try {

			Workbook wb = ExcelUtil.getWorkbookCompatible(excelPath);
			Sheet sheet = wb.getSheetAt(0);
			List<EnqQuoteItem> items = new ArrayList<EnqQuoteItem>();
			StringBuffer titleMsg = new StringBuffer();
			for (int i = 1; i <= sheet.getLastRowNum(); i++) {
				Row row = sheet.getRow(i);
				if (row == null) {
					continue;
				}
				EnqQuoteItem qi = new EnqQuoteItem();
				Cell enquiryItemIdCell = row.getCell(0);
				Cell productnameCell = row.getCell(1);
				Cell industryCell = row.getCell(2);
				Cell modelCell = row.getCell(3);
				Cell unitCell = row.getCell(4);
				Cell countCell = row.getCell(5);
				Cell unitpriceCell = row.getCell(6);
				Cell subtotalCell = row.getCell(7);
				if (productnameCell == null && industryCell == null && unitCell == null && unitpriceCell == null
						&& countCell == null) {
					continue;
				}
				if (productnameCell.getCellType() == HSSFCell.CELL_TYPE_BLANK
						&& industryCell.getCellType() == HSSFCell.CELL_TYPE_BLANK
						&& unitCell.getCellType() == HSSFCell.CELL_TYPE_BLANK
						&& unitpriceCell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
					continue;
				}
				if (unitpriceCell == null || unitpriceCell.getCellType() == HSSFCell.CELL_TYPE_BLANK || ExcelUtil.getStringCellValue(unitpriceCell) == null) {
					continue;
				}
				// 设备or产品名称
				if (productnameCell == null) {
					titleMsg.append("第" + i + "条产品,设备名称不能空!\\n");
					continue;
				}
				String productname = ExcelUtil.getStringCellValue(productnameCell);
				if (StringUtil.isEmpty(productname)) {
					titleMsg.append("第" + i + "条产品,设备名称不能空!\\n");
					continue;
				} else {
					qi.setProductName(productname);
				}
				// 品牌
				String brand = ExcelUtil.getStringCellValue(industryCell);
				//if (StringUtil.isEmpty(brand)) {
				//	titleMsg.append("第" + i + "条产品,品牌不能空!\n");
				//	continue;
				//} else {
				//}
					qi.setBrand(brand == null ? "" : brand);
				// 型号
				String model = ExcelUtil.getStringCellValue(modelCell);
				//if (StringUtil.isEmpty(model)) {
				//	titleMsg.append("第" + i + "条产品,型号不能空!\n");
				//	continue;
				//} else {
				//}
					qi.setModel(model == null ? "" : model);
				// 单位
				if (unitCell == null) {
					titleMsg.append("第" + i + "条产品,单位不能空!\\n");
					continue;
				}
				String unit = ExcelUtil.getStringCellValue(unitCell);
				if (StringUtil.isEmpty(unit)) {
					titleMsg.append("第" + i +"条产品,单位不能空!\\n");
					continue;
				} else {
					qi.setUnit(unit);
				}
				// 数量
				if (countCell == null || countCell.getCellType() != HSSFCell.CELL_TYPE_NUMERIC) {
					titleMsg.append("第" + i + "条产品,数量必须是数字且必填!\\n");
					continue;
				}
				// enquiryItemId
				if (enquiryItemIdCell != null && enquiryItemIdCell.getCellType() != HSSFCell.CELL_TYPE_NUMERIC) {
					titleMsg.append("第" + i + "条产品,编号必须是数字！!\\n");
					continue;
				}
				String eiicell = ExcelUtil.getStringCellValue(enquiryItemIdCell);
				if(!StringUtil.isEmpty(eiicell)){
					Integer enquiryItem = Integer.parseInt(eiicell);
					qi.setEnquiryItemId(enquiryItem);
					EnqEnquiryItem enqEnquiryItem = itemMapper.selectByPrimaryKey(enquiryItem);
					if (enqEnquiryItem == null) {
						titleMsg.append("第" + i +"条产品,编号:"+enquiryItem+"的清单项已不存在，采购商可能已修改询价单，请重新上传最新的报价单！\\n");
						continue;
					}
					if(enquiryId != null){
						if(enqEnquiryItem.getEnquiryId().compareTo(enquiryId) == 0){
							qi.setCategorySId(enqEnquiryItem.getCategorySId());
							qi.setCategoryName(categoryService.getCategorysById(qi.getCategorySId()).getName());
						}else{
							titleMsg.append("第" + i +"条产品,编号错误，不是该询价下的数据！采购商可能已修改询价单，请重新上传最新的报价单！\\n");
							continue;
						}
					}else{
						titleMsg.append("数据问题，询价Id不存在\\n");
						break;
					}
				}else{
					titleMsg.append("第" + i +"条产品,编号不为空!\\n");
					continue;
				}
				qi.setQuantity(CommonUtil.round(ExcelUtil.getDoubleCellValue(countCell) , 4 , BigDecimal.ROUND_HALF_UP));
				// 单价
				if (unitpriceCell == null || unitpriceCell.getCellType() != HSSFCell.CELL_TYPE_NUMERIC) {
					titleMsg.append("第" + i + "条产品,单价必须是数字且必填!\\n");
					continue;
				}
				qi.setUnitprice(CommonUtil.round(ExcelUtil.getDoubleCellValue(unitpriceCell) , 2 , BigDecimal.ROUND_HALF_UP));
				// 金额
				double subtotal = 0.0;
//				if (subtotalCell == null || (subtotalCell.getCellType() != HSSFCell.CELL_TYPE_FORMULA
//						&& subtotalCell.getCellType() != HSSFCell.CELL_TYPE_NUMERIC)) {
				subtotal = ExcelUtil.mul(qi.getQuantity(),qi.getUnitprice());
//				}else{
//					subtotal = ExcelUtil.getDoubleCellValue(subtotalCell);
//					BigDecimal bg = new BigDecimal(subtotal);
				//subtotal = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//					subtotal = bg.doubleValue();
//				}
				if (subtotal != 0) {
					qi.setTotalPrice(CommonUtil.round(subtotal , 2 , BigDecimal.ROUND_HALF_UP));
				} else {
					//2016.9.18 张栋  需求变更,为0的也可以上传
//					qi.setSubtotal(subtotal);
					continue;
				}
				// 技术参数描述
				Cell descrCell = row.getCell(8);
				if (descrCell != null){
					String dcl = ExcelUtil.getStringCellValue(descrCell);
					if(StringUtils.isNotBlank(dcl)){
						qi.setDescr(ExcelUtil.getStringCellValue(descrCell));
					}else{
						qi.setDescr("");
					}
				} else {
					qi.setDescr("");
				}
//				qi.setQuoteId(quoteId);
				items.add(qi);
			}

			if (items.isEmpty()) {
				titleMsg.append("没有可导入数据!\\n");
			} else {
				res.put("items", items);
			}
			if("".equals(titleMsg.toString())){
				res.put("success", true);
            }else{
				res.put("success", false);
            }
			res.put("msg", "".equals(titleMsg.toString()) ? "" : titleMsg.substring(0 , titleMsg.lastIndexOf("\\n")));
			return res;
		} catch (Exception e) {
			e.printStackTrace();
            if(e instanceof org.apache.poi.poifs.filesystem.OfficeXmlFileException){
                res.put("msg" , "文件分析时出错！");
            }
            if (e instanceof ServiceException) {
                throw (ServiceException) e;
            } else {
                LOGGER.error( "报价采析报错！", e);
                res.put("msg" , "文件“"+fileName+"”内容格式不正确，请确认模板是否被修改");
			}
		}

		return res;
	}

	//@Override
	//public Map<String, Object> getImportQuoteItems(File file, String fileName) {
	//	return null;
	//}

    @Override
    public List<EnqQuoteDetail> getProjPurchaseQuoteDetail(Integer enqid) {
        return enqBudgetMapper.getProjPurchaseQuoteDetail(enqid);
    }

    @Override
    public EnqQuote getEnqQuoteById(Integer quoteid) {
    	return enqQuoteMapper.getQuoteByid(quoteid);
    }

    @Override
    public List<EnqQuoteItemExt> getEnqQuoteItemExt(Integer quoteid) {
        return enqQuoteMapper.getEnqQuoteItemExt(quoteid);
    }

	@Override
	public List<EnqPurchaseRecommend> getEnqRecommend(Integer companyid) {
		return enquiryMapper.getEnqRecommend(companyid);
	}

    @Override
    public EnqEnquiry getEnqEnquiryByIdWidthItem(Integer enqid) {
        return enquiryMapper.getEnqEnquiryByIdWidthItem(enqid,null);
    }

    @Override
    public EnqEnquiry getEnqEnquiryByIdWidthItem(Integer enqid, Integer userid) {
        return enquiryMapper.getEnqEnquiryByIdWidthItem(enqid,userid);
    }

    @Override
    public List<EnqCatChoose> getEnqCatChoose(Integer enqid) {
        return enqQuoteMapper.getEnqCatChoose(enqid);
    }

	@Override
	public List<EnqCatChoose> getQuoteCatChoose(Integer quoteid) {
		return  enqQuoteMapper.getQuoteCatChoose(quoteid);
	}



	/**
	 * 构造询价清单表头
	 *
	 * @return
	 */
	private List<Map<String, Object>> generateQuoteItemTitles() {
		List<Map<String, Object>> titles = new ArrayList<Map<String, Object>>();
		/* imteId(必填) */
		Map<String, Object> idMap = new HashMap<String , Object>();
		idMap.put("title", "编号");
		idMap.put("red", true);
		titles.add(idMap);
		/* 系统(必填) */
//		Map<String, Object> categroyMap = new HashMap<String , Object>();
//		categroyMap.put("title", "系统");
//		categroyMap.put("red", true);
//		titles.add(categroyMap);
		/* 设备名称(必填) */
		Map<String, Object> productMap = new HashMap<String , Object>();
		productMap.put("title", "设备名称");
		productMap.put("red", true);
		titles.add(productMap);
		/* 品牌 */
		Map<String, Object> brandMap = new HashMap<String, Object>();
		brandMap.put("title", "品牌");
		//brandMap.put("red", true);
		titles.add(brandMap);
		/* 型号 */
		Map<String, Object> modelMap = new HashMap<String, Object>();
		modelMap.put("title", "型号");
		//modelMap.put("red", true);
		titles.add(modelMap);
		/* 单位(必填) */
		Map<String, Object> unitMap = new HashMap<String, Object>();
		unitMap.put("title", "单位");
		unitMap.put("red", true);
		titles.add(unitMap);
		/* 数量(必填) */
		Map<String, Object> countMap = new HashMap<String, Object>();
		countMap.put("title", "数量");
		countMap.put("red", true);
		titles.add(countMap);
		/* 单价(必填) */
		Map<String, Object> unitpriceMap = new HashMap<String, Object>();
		unitpriceMap.put("title", "单价");
		unitpriceMap.put("red", true);
		titles.add(unitpriceMap);
		/* 金额(必填) */
		Map<String, Object> subtotalMap = new HashMap<String, Object>();
		subtotalMap.put("title", "金额");
		subtotalMap.put("red", true);
		titles.add(subtotalMap);
		/* 技术参数描述 */
		Map<String, Object> descrMap = new HashMap<String, Object>();
		descrMap.put("title", "技术参数描述");
		titles.add(descrMap);
		return titles;
	}


	/**
	 * 构造询价清单表头
	 *
	 * @return
	 */
	private List<Map<String, Object>> generateQuoteItemTitlesForTest() {
		List<Map<String, Object>> titles = new ArrayList<Map<String, Object>>();
		/* imteId(必填) */
		Map<String, Object> idMap = new HashMap<String , Object>();
		idMap.put("title", "编号");
		idMap.put("red", true);
		titles.add(idMap);
		/* 系统(必填) */
		Map<String, Object> categroyMap = new HashMap<String , Object>();
		categroyMap.put("title", "系统");
//		categroyMap.put("red", true);
		titles.add(categroyMap);
		/* 设备名称(必填) */
		Map<String, Object> productMap = new HashMap<String , Object>();
		productMap.put("title", "设备名称");
		productMap.put("red", true);
		titles.add(productMap);
		/* 品牌 */
		Map<String, Object> brandMap = new HashMap<String, Object>();
		brandMap.put("title", "品牌");
		//brandMap.put("red", true);
		titles.add(brandMap);
		/* 型号 */
		Map<String, Object> modelMap = new HashMap<String, Object>();
		modelMap.put("title", "型号");
		//modelMap.put("red", true);
		titles.add(modelMap);
		/* 单位(必填) */
		Map<String, Object> unitMap = new HashMap<String, Object>();
		unitMap.put("title", "单位");
		unitMap.put("red", true);
		titles.add(unitMap);
		/* 数量(必填) */
		Map<String, Object> countMap = new HashMap<String, Object>();
		countMap.put("title", "数量");
		countMap.put("red", true);
		titles.add(countMap);
		/* 单价(必填) */
		Map<String, Object> unitpriceMap = new HashMap<String, Object>();
		unitpriceMap.put("title", "单价");
		unitpriceMap.put("red", true);
		titles.add(unitpriceMap);
		/* 金额(必填) */
		Map<String, Object> subtotalMap = new HashMap<String, Object>();
		subtotalMap.put("title", "金额");
		subtotalMap.put("red", true);
		titles.add(subtotalMap);
		/* 技术参数描述 */
		Map<String, Object> descrMap = new HashMap<String, Object>();
		descrMap.put("title", "技术参数描述");
		titles.add(descrMap);
		return titles;
	}

	class EnqEnquiryitemRendererTest implements ExcelUtil.RowRenderer<EnqEnquiryItem> {

		@Override
		public void render(HSSFRow row, EnqEnquiryItem item) {

			HSSFCellStyle style = row.getRowStyle();
			style.setLocked(false);


			// 编号
			HSSFCell idCell = row.createCell(0, HSSFCell.CELL_TYPE_NUMERIC);
			idCell.setCellValue(item.getId());

			HSSFCell categoryCell = row.createCell(1, HSSFCell.CELL_TYPE_NUMERIC);
			categoryCell.setCellValue(item.getCategorySName());
			categoryCell.setCellStyle(style);

			// 设备名称
			HSSFCell productCell = row.createCell(2, HSSFCell.CELL_TYPE_STRING);
			productCell.setCellValue(item.getProductName());

			int rowNum = row.getRowNum();

			// 品牌
			HSSFCell industryCell = row.createCell(3, HSSFCell.CELL_TYPE_STRING);
			industryCell.setCellValue(item.getBrand());
			industryCell.setCellStyle(style);
			// 型号
			HSSFCell modelCell = row.createCell(4, HSSFCell.CELL_TYPE_STRING);
			modelCell.setCellValue(item.getModel());
			modelCell.setCellStyle(style);
			// 单位
			HSSFCell unitCell = row.createCell(5, HSSFCell.CELL_TYPE_STRING);
			unitCell.setCellValue(item.getUnit());
			unitCell.setCellStyle(style);

			// 数量
			HSSFCell countCell = row.createCell(6, HSSFCell.CELL_TYPE_NUMERIC);
			countCell.setCellValue(item.getQuantity()==null?0:item.getQuantity());
			countCell.setCellStyle(style);
			// 单价
			HSSFCell unitpriceCell = row.createCell(7, HSSFCell.CELL_TYPE_NUMERIC);
			unitpriceCell.setCellValue("");
			unitpriceCell.setCellStyle(style);

			// 金额
			HSSFCell totalCell = row.createCell(8, HSSFCell.CELL_TYPE_NUMERIC);
			totalCell.setCellValue(0);
			totalCell.setCellStyle(style);
			if (rowNum >= 1) {
				rowNum += 1;
				// String cellFormula = "ROUND(E"+rowNum+"*F"+rowNum+")";
				String cellFormula = "G" + rowNum + "*H" + rowNum;
				totalCell.setCellFormula(cellFormula);
			}
			// 技术参数描述
			HSSFCell descrCell = row.createCell(9, HSSFCell.CELL_TYPE_STRING);
			descrCell.setCellValue(item.getDescr());
			descrCell.setCellStyle(style);
		}

	}

	class EnqEnquiryitemRenderer implements ExcelUtil.RowRenderer<EnqEnquiryItem> {

		@Override
		public void render(HSSFRow row, EnqEnquiryItem item) {

			HSSFCellStyle style = row.getRowStyle();
			style.setWrapText(true);
			style.setLocked(false);


			// 编号
			HSSFCell idCell = row.createCell(0, HSSFCell.CELL_TYPE_NUMERIC);
			idCell.setCellValue(item.getId());
//			idCell.setCellStyle(style2);

			// 设备名称
			HSSFCell productCell = row.createCell(1, HSSFCell.CELL_TYPE_STRING);
			productCell.setCellValue(item.getProductName());
//			productCell.setCellStyle(style2);

			int rowNum = row.getRowNum();

			// 品牌
			HSSFCell industryCell = row.createCell(2, HSSFCell.CELL_TYPE_STRING);
			industryCell.setCellValue(item.getBrand());
			industryCell.setCellStyle(style);
			// 型号
			HSSFCell modelCell = row.createCell(3, HSSFCell.CELL_TYPE_STRING);
			modelCell.setCellValue(item.getModel());
			modelCell.setCellStyle(style);
			// 单位
			HSSFCell unitCell = row.createCell(4, HSSFCell.CELL_TYPE_STRING);
			unitCell.setCellValue(item.getUnit());
			unitCell.setCellStyle(style);

			// 数量
			HSSFCell countCell = row.createCell(5, HSSFCell.CELL_TYPE_NUMERIC);
			countCell.setCellValue(item.getQuantity()==null?0:item.getQuantity());
			countCell.setCellStyle(style);
			// 单价
			HSSFCell unitpriceCell = row.createCell(6, HSSFCell.CELL_TYPE_NUMERIC);
			unitpriceCell.setCellValue("");
			unitpriceCell.setCellStyle(style);

			// 金额
			HSSFCell totalCell = row.createCell(7, HSSFCell.CELL_TYPE_NUMERIC);
			totalCell.setCellValue(0);
			totalCell.setCellStyle(style);
			if (rowNum >= 1) {
				rowNum += 1;
				// String cellFormula = "ROUND(E"+rowNum+"*F"+rowNum+")";
				String cellFormula = "F" + rowNum + "*G" + rowNum;
				totalCell.setCellFormula(cellFormula);
			}
			// 技术参数描述
			HSSFCell descrCell = row.createCell(8, HSSFCell.CELL_TYPE_STRING);
			descrCell.setCellValue(item.getDescr());
			descrCell.setCellStyle(style);
		}

	}

	@Override
	public Pagination getEnqProjectItemByCompanyId(int pageNo, int pageSize, Integer companyId,Map<String, String> searchMap) {
		Page<Object> startPage = PageHelper.startPage(pageNo, pageSize);
		String keyword = searchMap.get("so_keyword");
		String sdate = searchMap.get("so_sdate");
		String endate = searchMap.get("so_endate");

		List<EnProjectShowItem> enqProjectItem = enqProjectMapper.getEnqProjectItemByCompanyId(companyId,keyword,sdate,endate);

		Pagination p = new Pagination(startPage,enqProjectItem);
		p.setList(enqProjectItem);
		p.setParams(searchMap);
		return p;

	}

	@Override
	public Pagination getBackEnquiryList(Map<String, String> searchMap , Integer pageNo, Integer pageSize) {

		Page<Object> startPage = PageHelper.startPage(pageNo, pageSize);

		List<Map<String, Object>> backEnquiryList = enquiryMapper.getBackEnquiryList(searchMap);

		Pagination p = new Pagination(startPage,backEnquiryList);
		p.setList(backEnquiryList);
		p.setParams(searchMap);
		return p;

	}

	@Override
	public Integer getBackEnquiryListNum(Map<String, String> searchMap) {
		return enquiryMapper.getBackEnquiryListNum(searchMap);
	}


	//2016.12.13  张栋 更改转发采购询价为  跳转采购询价,进行再编辑
	@Override
	public EnqEnquiry budgetTopurchase(Integer budgetid, String deadtime, Integer userId, Integer companyId) throws Exception {
		EnqBudget budget = enqBudgetMapper.selectByPrimaryKey(new EnqBudget(budgetid));
		//拿倒询价信息,设置新的时间后重新插入
		EnqEnquiry enq = enquiryMapper.selectByPrimaryKey(new EnqEnquiry(budget.getEnquiryId()));
		enq.setId(null);
		enq.setQtype(2);//采购
		enq.setCustomerId(companyId);
		enq.setUserId(userId);
        //设置一个默认payment 支付方式
        enq.setPayment(1);
		//默认公开
		//enq.setPubtype(1);

//		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//		simpleDateFormat.parse(deadtime);
//		enq.setDeadline(simpleDateFormat.parse(deadtime));
//		enquiryMapper.insert(enq);

		//取到预算详情
		EnqBudgetItem item = new EnqBudgetItem();
		item.setBudgetId(budgetid);
		List<EnqBudgetItem> items = enqBudgetItemMapper.select(item);

		Integer enqId = enq.getId();//取到为null,就是要设置为null
		Integer projectId = enq.getProjectId();
		List<EnqEnquiryItem> all = new ArrayList<>();
		//根据预算详情,获取询价详情
		for (EnqBudgetItem enqBudgetItem : items) {
			Integer quoteId = enqBudgetItem.getQuoteId();
			Integer categroyId = enqBudgetItem.getCategroyId();
			List<EnqEnquiryItem> qitems = itemMapper.getEItemByQItem(quoteId,categroyId);
			all.addAll(qitems);
		}

		//为每个Item关联上询价表
		for (EnqEnquiryItem qitem : all) {
			qitem.setEnquiryId(enqId);
			qitem.setProjectId(projectId);
//			itemMapper.insert(qitem);
		}
//		itemMapper.batchSave(all);
        enq.setItems(all);
		return enq;
	}

    @Override
    public void saveQuoteItemList(List<EnqQuoteItem> items) throws Exception {
    	double total = 0;
		for (EnqQuoteItem item : items) {
			if(item.getId() == null){
				item.setCreatetime(new Date());
				enqQuoteItemMapper.insert(item);
				total = total + item.getTotalPrice();
			}
		}
		if(total > 0){
			EnqQuote quote = enqQuoteMapper.getQuoteByid(items.get(0).getQuoteId());
			quote.setTotalPrice(total);
			enqQuoteMapper.updateByPrimaryKey(quote);
		}
    }

	@Override
	public void passQuoteAndItems(List<EnqQuoteItem> items, Integer quoteId) throws Exception {
		EnqQuote quote = enqQuoteMapper.getQuoteByid(quoteId);
		if(quote.getState().compareTo(EnqQuoteEnum.QUT_STAY.getIndex()) == 0){
			//changeQuoteState(quote.getId() , EnqQuoteEnum.QUT_POSTED.getIndex());
			Example exp = new Example(EnqQuoteItem.class);
			exp.createCriteria().andEqualTo("quoteId" , quote.getId());
			enqQuoteItemMapper.deleteByExample(exp);
			saveQuoteItemList(items);
		}else{
			throw  new Exception("报价状态出错，非待审核状态");
		}
	}

	@Override
	public void changeQuoteState(Integer quoteId, Integer state , String suggest) throws Exception {
		EnqQuote quote = enqQuoteMapper.getQuoteByid(quoteId);
		Integer oldState = quote.getState();
		quote.setSuggest(suggest);
		quote.setState(state);
		EnqEnquiry enquiry = enquiryMapper.getEnqEnquiryById(quote.getEnquiryId());
		if(state.compareTo(EnqQuoteEnum.QUT_POSTED.getIndex()) == 0){//当审核通过的时候  给采购商发送消息
			User user = userService.getUserByQuoteId(quoteId);
			Company provider = companyService.getCompanyById(quote.getCompanyId());
			if(user != null && enquiry != null && provider != null){
				Map<String , String > params = new HashMap<String , String >();
				params.put("provider" , provider.getCompanyName());
				params.put("enquiry" , enquiry.getEnquiryName());
				UserMsgDto d = new UserMsgDto(user.getId() , user.getMobile() , user.getEmail());
				msgConfigService.sendMessage("NOTICE_HAVE_OFFER" , params , null , Arrays.asList(d),needely());
			}
			/**
			 * 通过审核赠送积分
			 */
			if (quote.getFirstpass().compareTo(Company.FISRT_PASS) == 0) {//第一次通过的时候送积分
				integralService.addUserRecord(quote.getUserId(), "quote_lists", null, null, null);
				quote.setFirstpass(0);
			}
		}
		if (state.compareTo(EnqQuoteEnum.QUT_REFUSE.getIndex()) == 0) {//当审核不通过时   给供应商发消息
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Map<String , String > params = new HashMap<String , String >();
			params.put("pubtime", sdf.format(quote.getQuoteDate()));
			params.put("quotetitle" , enquiry.getEnquiryName());
			params.put("backreason" , suggest == null ? "" : suggest);
			msgConfigService.sendMessage("AUDIT_QUOTE_NOPASS" , params , null , Arrays.asList(quote.getUserId()),needely());
		}
		enqQuoteMapper.updateByPrimaryKey(quote);

	}



	@Override
	public List<EnqQuoteItem> getItemByQuote(Integer quoteId) {
		return enqQuoteItemMapper.getItemByQuote(quoteId);
	}

	@Override
	public boolean closeProject(Integer projectId) {

		// 判断订单,有待付款订单则不能更新
		//'订单状态：0-已关闭；1-待付款；2-已付款 ；3已发货;4已完成',
		int count = enqProjectMapper.getOrderInfoCount(projectId,null);
		if(count!=0){
			return false;
		}

		//
		/**
		 *关闭项目
		 * 1.项目本身状态,关闭
		 * 2.项目下询价,预算,关闭
		 * 3.询价,预算对应的报价表,关闭
		 */
		//1
		try {
			EnqProject p = new EnqProject();
			p.setId(projectId);
			p.setState(2);
			enqProjectMapper.updateByPrimaryKeySelective(p);
			//2
			//询价
			EnqEnquiry ee = new EnqEnquiry();
			//'状态 0:待审核,1:已发布,2:不通过,3:重新审核4：已关闭 5：已截止',
			ee.setState(4);
			Example example = new Example(EnqEnquiry.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("projectId",projectId);
			enquiryMapper.updateByExampleSelective(ee,example);
			//预算暂时不管,因为预算不会推送给报价方
			//3
			//2017.2.7号,孙俊 不关闭
			//2017.3.20 杨程 张栋 关闭报价
			EnqQuote  quote = new EnqQuote();
			//'0.审核中（待审核）1.比价中（审核能过） 2.已取消3.审核未通过4.已下单5.报价未采纳6.询价已取消',
			quote.setState(6);
			Example example1 = new Example(EnqQuote.class);
			Example.Criteria criteria1 =example1.createCriteria();
			criteria1.andEqualTo("projectId",projectId);
			enqQuoteMapper.updateByExampleSelective(quote,example1);

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	@Autowired
	private MqProducerService mq;

	@Value("${sms.delay.start}")
	private String start;

	@Value("${sms.delay.end}")
	private String end;

	private static final SimpleDateFormat sdf = new SimpleDateFormat("HHmm");

	@Override
	public boolean needely(){
		Calendar ca = Calendar.getInstance();
		Date time = ca.getTime();
		String format = sdf.format(time);
		int nowtime = Integer.parseInt(format);
		int startime = Integer.parseInt(start);
		int endtime = Integer.parseInt(end);

		boolean needely=true;//是否延迟发送
		if(nowtime>startime && nowtime < endtime){
			needely = false;
		}
		return needely;
	}



	private List<Integer> getAllCompanyUsers(Integer companyid){
		//获取公司下的所有子公司
		List<Company> companies = companyService.allBranchCompany(companyid);
		List<Integer> users = new ArrayList<>();
		if(companies!=null){
			for (Company which : companies) {
				Integer isprovider = which.getIsprovider();
				if(isprovider==1){
					List<User> listuser = userService.getUsersBYCompanyId(which.getId());
					for (int i = 0; i < listuser.size(); i++) {
						users.add(listuser.get(i).getId());
					}
				}
			}
		}
		return users;
	}
	/**
	 * 公开发送短信, 设计需求
	 * Created by 张栋 on 2016/11/28 15:05
	 */
	@Override
	public Integer getNeedPubSMS(Integer enquiryid, String url,boolean ifsend) {
		//获取项目所在地
		EnqEnquiry e = new EnqEnquiry(enquiryid);
		EnqEnquiry enqEnquiry = enquiryMapper.selectByPrimaryKey(e);
		EnqProjectExt p = enqProjectMapper.getEnqProjectExtById(enqEnquiry.getProjectId());
		EnqProject enqProject = enqProjectMapper.selectByPrimaryKey(p);
		String provinceCode = enqProject.getAreaProvince();
		//根据地区code 与  u_msg_enquiry_send  查 接受人
		//询价类型
		Integer qtype = enqEnquiry.getQtype();

		List<Integer> enqSIds = enquiryMapper.getEnqCategorySids(enquiryid);

		if(enqSIds==null ||enqSIds.size()==0){
			return 0;
//			throw  new RuntimeException("查不到该询价涉及到的系统!");
		}

		//排除发送人集团公司里所有的用户
		Integer customerId = enqEnquiry.getCustomerId();
		Company company = companyService.getTopParentCompany(customerId);
		List<Integer> excludeuserid = getAllCompanyUsers(company.getId());
		if(excludeuserid.isEmpty()){
			excludeuserid=null;
		}
		List<Integer>  userids = enquiryMapper.getMsgEnquirySend(provinceCode,qtype,enqSIds,excludeuserid);

		if(userids==null)userids=new ArrayList<>();

		if(!ifsend){//
			return userids.size();
		}

		Map<String,String> params = new HashMap<>();
		//公司名称
		params.put("company",p.getCompanyName());
		//询价名称
		params.put("enquirytitle",enqEnquiry.getEnquiryName());
		if(qtype==1){
			params.put("requesttype","预算询价");
		}else{
			params.put("requesttype","采购询价");
		}

		//公开发送
		msgConfigService.sendMessage("ENQ_STAT_PUBLIC",params,url,userids,needely());
		try {
			MailParam  mailParam = new MailParam();
			mailParam.setTo("115530346@qq.com");
			mailParam.setSubject("公开发送:"+enqEnquiry.getEnquiryName()+" 类别:"+params.get("requesttype"));
			mailParam.setContent("发送ENQ_STAT_PUBLIC记录共"+userids.size());
			mq.sendMailMessage(mailParam);
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
		}

		return userids.size();
	}

	/**
	 * 非公开发布
	 * Created by 张栋 on 2016/11/28 15:26
	 */
	@Override
	public Integer getNeedSMS(Integer enquiryid, String url,boolean ifsend) {
		EnqEnquiry e = new EnqEnquiry(enquiryid);
		EnqEnquiry enqEnquiry = enquiryMapper.selectByPrimaryKey(e);
		EnqProjectExt p = enqProjectMapper.getEnqProjectExtById(enqEnquiry.getProjectId());

		//邀请的商家
		List<UserEnum> userenum = new ArrayList<>();
		userenum.add(UserEnum.cadmin);
		userenum.add(UserEnum.saler);
		String inviteCids = enqEnquiry.getInviteCids();
		String inviteTels = enqEnquiry.getInviteTels();

		//邀请的商家
		List<String> mobiles = new ArrayList<>(); // 用来给下面的邀请手机号去重用的
		List<Integer> userids = new ArrayList<>();
		if(StringUtils.isNotBlank(inviteCids)){
			String[] split = inviteCids.split(",");
			for (String s : split) {
				//根据公司id 获取当前公司下的,  管理员与销售
				List<UserAuthority> author = userService.getUserAuthorityByCompanyId(Integer.parseInt(s), userenum);
				for (int i1 = 0; i1 < author.size(); i1++) {
					UserAuthority userAuthority = author.get(i1);
					User u = userAuthority.getUser();
					Integer userid = u.getId();
					String mobile = u.getMobile();
					if(StringUtils.isNotBlank(mobile)){
						mobiles.add(mobile);
					}
					userids.add(userid);
				}
			}
		}
		//邀请的手机号
		List<UserMsgDto > dtos = new ArrayList<>();
		if(StringUtils.isNotBlank(inviteTels)){
			String[] telss = inviteTels.split(",");
			for (int i = 0; i < telss.length; i++) {
				String tel = telss[i];
				if(!mobiles.contains(tel)){
					UserMsgDto dto = new UserMsgDto();
					dto.setMobile(tel);
					dtos.add(dto);
				};
			}
		}


		if(!ifsend){//
			return userids.size()+dtos.size();
		}

		Map<String,String> params = new HashMap<>();
		//公司名称
		params.put("company",p.getCompanyName());
		//询价名称
		params.put("enquirytitle",enqEnquiry.getEnquiryName());

		Integer qtype = enqEnquiry.getQtype();
		if(qtype==1){
			params.put("requesttype","预算询价");
		}else{
			params.put("requesttype","采购询价");
		}
		msgConfigService.sendMessage("ENQ_STAT_PUBLIC",params,url,userids,needely());
		msgConfigService.sendMessage("ENQ_STAT_PUBLIC",params,url,dtos,needely());

		try {
			MailParam  mailParam = new MailParam();
			mailParam.setTo("115530346@qq.com");
			mailParam.setSubject("非公开发布:"+enqEnquiry.getEnquiryName()+" 类别:"+params.get("requesttype"));
			mailParam.setContent("发送记录共"+(userids.size()+dtos.size()));
			mq.sendMailMessage(mailParam);
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
		}
		return userids.size()+dtos.size();
	}

	@Override
	public boolean closeEnquiry(Integer enqid) {
		//判断有没有订单
		int count = enqProjectMapper.getOrderInfoCountEnquiry(enqid,null);
		if(count!=0){
			return false;
		}

		//关闭自己
		EnqEnquiry enqEnquiry = new EnqEnquiry(enqid);
		enqEnquiry.setState(4);
		enquiryMapper.updateByPrimaryKeySelective(enqEnquiry);
		enqEnquiry = enquiryMapper.getEnqEnquiryById(enqid);
		Integer userid = enqEnquiry.getUserId();
		if(userid!=null){
			integralService.addUserRecord(userid, "user_cancel_lists",null,null, null);
		}

/*
		2017.2.7号,孙俊*/
		//关闭报价
		//0待审核1.启用 2.关闭报价
        EnqQuote  quote = new EnqQuote();

		//2017.3.20 杨程,张栋
        quote.setState(6);
        //0待审核1.启用 2.关闭报价
        Example example1 = new Example(EnqQuote.class);
        Example.Criteria criteria1 =example1.createCriteria();
        criteria1.andEqualTo("enquiryId",enqid);
        enqQuoteMapper.updateByExampleSelective(quote,example1);

        return true;
	}

    @Override
    public void saveWatchQuote(EnqQuote quote) {
    	if(quote != null && quote.getId() != null){
			quote.setConsulttime(new Date());
			enqQuoteMapper.updateByPrimaryKey(quote);
		}
    }

	@Override
	public List<EnqEnquiry> getTaskEnqByStates() {
		//除去  已经关闭的,已经截止的,其他都要变成 已截止的
		List<Integer> states = new ArrayList<>();
		states.add(0);
		states.add(1);
		states.add(2);
		states.add(3);

		return enquiryMapper.getTaskEnqByStates(states);
	}

	@Override
	public List<Map> searchXmh(Map param) {
		/*String categorySId = Conver.toStr(param.get("categorySId"));
		if(StrUtil.isNotBlank(categorySId)) {
			String[] array = categorySId.split(",");
			param.put("categorySIdArray", array);
		}*/
		return enquiryMapper.searchXmh(param);
	}

    @Override
    public List<Map> getFocusCompanys(Integer enquiryId, Integer orderDown) {
        return enquiryMapper.getFocusCompanys(enquiryId, orderDown);
    }

    @Override
    public List<PushEnquiryListDto> getNewPush(Integer companyId , Integer pageSize) {
        return enquiryMapper.getNewPush(companyId , pageSize);
    }

    @Override
	public Integer getQuoteCountByType(Integer userid, Integer qtype) {
		return enqQuoteMapper.getQuoteCountByUserAndQtype(userid,qtype);
	}

	@Override
	public boolean hasQuote(int companyId, int enquiryId) {
		EnqQuote quote = new EnqQuote();
		quote.setEnquiryId(enquiryId);
		quote.setCompanyId(companyId);
		Example example = new Example(EnqQuote.class);
		example.createCriteria().andEqualTo(quote).andNotEqualTo("state", EnqQuoteEnum.QUT_CLOSE.getIndex());
		int count = enqQuoteMapper.selectCountByExample(example);
		return count > 0 ;
	}

	@Override
	public AjaxJson canQuote(User user, List<Role> roleList, Company company, Role currentRole, int enquiryId) {
		if(user == null || currentRole == null || CollectionUtil.isEmpty(roleList)) {
            return AjaxJson.error("请先登录").setObj("login");
		}
		if(company == null) {
            return AjaxJson.error("您尚未绑定任何企业信息，无法进行操作").setObj("companyInfo");
		}
		boolean hasProviderRole = false;
		for(Role role : roleList) {
			if(role != null && role.getRoleType().intValue() == RoleTypeEnum.PROVIDER.getValue()) {
				hasProviderRole = true;
				break;
			}
		}
		if(!hasProviderRole) {
            return AjaxJson.error("采购商是不可以进行报价的，请您谅解！");
		}
		if(company.getAuditState().intValue() != CompanyAuditStateEnum.PASS.getValue()) {
            return AjaxJson.error("您的企业资料尚未通过审核，无法报价").setObj("companyInfo.view");
		}
		EnqEnquiry enquiry = enquiryMapper.selectByPrimaryKey(enquiryId);
		if(enquiry == null || enquiry.getRemoved().intValue() == 1) {
            return AjaxJson.error("该询价不允许报价");
		}
		if(enquiry.getState().intValue() == EnqEnquiryEnum.ENQ_STAY.getIndex() || enquiry.getState().intValue() == EnqEnquiryEnum.ENQ_RETRY.getIndex()) {
            return AjaxJson.error("询价尚在审核中，请稍后再试！");
		}
		if(enquiry.getState().intValue() == EnqEnquiryEnum.ENQ_BACK.getIndex()) {
			return AjaxJson.error("询价单未通过审核，请稍后再试");
		}
		if(enquiry.getState().intValue() == EnqEnquiryEnum.ENQ_CLOSED.getIndex()) {
            return AjaxJson.error("询价已结束！");
		}
		if(enquiry.getState().intValue() == EnqEnquiryEnum.ENQ_OVER.getIndex()) {
            return AjaxJson.error("询价已完成！");
		}
		if(company.getId().intValue() == enquiry.getCustomerId().intValue()) {
            return AjaxJson.error("您无法对自己的询价单进行报价");
		}
		if(companyService.isChildCompany(company.getId(), enquiry.getCustomerId())) {
			return AjaxJson.error("您无法对分公司的询价单进行报价");
		}
		EnqProject project = enqProjectMapper.selectByPrimaryKey(enquiry.getProjectId());
		if(project == null) {
            return AjaxJson.error("该询价不允许报价");
		}
		/*boolean inThisArea = false;
		//获取公司的经营地区
		List<CompanyBusiness> companyBusinessList = companyBusinessMapper.selectByCompanyId(company.getId());
		for(CompanyBusiness companyBusiness : companyBusinessList) {
			if(StrUtil.equals(companyBusiness.getProvinceCode(), project.getAreaProvince())) {
				inThisArea = true;
				break;
			}
		}
		if(!inThisArea) {
            return AjaxJson.error("该询价的所在地不位于您的经营地区内");
		}*/
		if(hasQuote(company.getId(), enquiryId)) {
            return AjaxJson.error("您已参与报价！");
		}
		/*boolean hasThisCate = false;
		//获取公司的主营系统
		List<CompanyCategory> categoryList = companyCategoryService.findCategoryByCompanyId(company.getId());
		//获取询价的系统
		EnqEnquiryItem item = new EnqEnquiryItem();
		item.setEnquiryId(enquiryId);
		List<EnqEnquiryItem> enquiryItemList = itemMapper.select(item);
		for(EnqEnquiryItem enquiryItem : enquiryItemList) {
			Integer itemCateId = enquiryItem.getCategorySId();
			if(!hasThisCate && itemCateId != null) {
				for(CompanyCategory companyCategory : categoryList) {
					if(companyCategory.getCategoryId() != null && companyCategory.getCategoryId().equals(itemCateId)) {
						hasThisCate = true;
						break;
					}
				}
			}
		}
		if(!hasThisCate) {
            return AjaxJson.error("当前采购商发布的询价所涉及的系统未在您选择的主营业务中");
		}*/
		if(enquiry.getPubtype() != null && enquiry.getPubtype().intValue() == 2 && !("," + enquiry.getInviteCids() + ",").contains("," + company.getId() + ",")) {
            return AjaxJson.error("您无发对该询价报价");
		}

        EnqEnquiry enq = enquiryMapper.categorySure(enquiryId, company.getId());
        if (enq == null) {
            return AjaxJson.error("您所经营的系统不在此询价范围内，无法进行报价");
        }

        return AjaxJson.success();
	}

    @Override
    public void updateEnqDowsCus(Integer companyId, Integer enqId) {
        if(companyId != null && enqId != null){
			EnqEnquiry enq = enquiryMapper.selectByPrimaryKey(enqId);
			if(enq != null){
				String docus = enq.getDownListCus();
				if(StrUtil.isNotBlank(docus)){
					if(docus.indexOf(","+companyId+",") == -1){
						enq.setDownListCus(docus + companyId +",");
					}
				}else{
					enq.setDownListCus("," + companyId +",");
				}
				enquiryMapper.updateByPrimaryKey(enq);
			}
		}
    }

    @Override
    public Integer getQuoteCountEnqStat(Integer enqid, int quotestat) {
        //0待审核1.启用 2.关闭报价
        Example example1 = new Example(EnqQuote.class);
        Example.Criteria criteria1 =example1.createCriteria();
        criteria1.andEqualTo("enquiryId",enqid);
        criteria1.andEqualTo("state",quotestat);
        return enqQuoteMapper.selectCountByExample(example1);
    }

	@Override
	public List<EcharsProjectArea> projectArea() {
		List<EcharsProjectArea> echarsProjectAreas = enquiryMapper.projectArea();
		for (EcharsProjectArea echarsProjectArea : echarsProjectAreas) {
			String value = echarsProjectArea.getValue();
			if(StringUtils.isBlank(value)){
				String name = echarsProjectArea.getName();
				String aaa = null;
				try {
					aaa = URLEncoder.encode(name, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				String request = request("http://apis.baidu.com/xiaogg/citylocation/citylocation", "city=" + aaa);
				JSONObject jsonObject = JSONObject.parseObject(request);
				String x = jsonObject.getString("x");
				String y = jsonObject.getString("y");
				echarsProjectArea.setX(x);
				echarsProjectArea.setY(y);
				echarsProjectArea.setValue(x+","+y+","+echarsProjectArea.getCount());
				enquiryMapper.updateEcharsGrid(echarsProjectArea.getId(),x,y);
			}
		}
		return enquiryMapper.projectArea();
	}

	@Override
	public List<EnqProject> getEnqProjectByName(String projectname, Integer userid) {
		EnqProject project = new EnqProject();
		project.setProjectName(projectname);
		project.setUserId(userid);
		return enqProjectMapper.select(project);
	}

	public static void main(String[] args){
		String aaa = null;
		try {
			//{"x":"118.769502","y":"32.066586"}  {"x":"118.778074","y":"32.057236"}
			aaa = URLEncoder.encode("南京", "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		request("http://apis.baidu.com/xiaogg/citylocation/citylocation", "city=" + aaa);
	}
	public static String request(String httpUrl, String httpArg) {
		BufferedReader reader = null;
		String result = null;
		StringBuffer sbf = new StringBuffer();
		httpUrl = httpUrl + "?" + httpArg;

		try {
			URL url = new URL(httpUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			// 填入apikey到HTTP header
			connection.setRequestProperty("apikey",  "823bcb545cd817c40562cf1d73300357");
			connection.connect();
			InputStream is = connection.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			String strRead = null;
			while ((strRead = reader.readLine()) != null) {
				sbf.append(strRead);
				sbf.append("\r\n");
			}
			reader.close();
			result = sbf.toString();
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public List<EnqEnquiry> listEnquiryBySize(int size) {
		return enquiryMapper.selectBySize(size);
	}
}
